<?php

namespace App\Http\Controllers\Site\Custom\Provider;
use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Business\GoodsCategory;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use Validator;

class CategoryController extends Controller
{
    use HelperControllerBuildTrait;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $master = Auth::user()->store->categories()->MasterList()->paginate($request->query('pageSize'));

        if (\Request::ajax()) {
            $data = [];

            foreach ($master as $item) {
                $data[] = [
                    'id'         => $item->id,
                    'name'       => $item->name,
                    'is_visible' => $item->display,
                    'sort'       => $item->sort,
                    'oper'       => 0,
                    'has_child'  => $item->children->count() > 0 ? true : false,
                    'children'   => call_user_func_array(function ($items) {
                        $data = [];
                        foreach ($items as $item) {
                            $data[] = [
                                'id'         => $item->id,
                                'name'       => $item->name,
                                'is_visible' => $item->display,
                                'sort'       => $item->sort,
                                'oper'       => 1,
                            ];
                        }

                        return $data;
                    }, [$item->children]),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'    => $master->currentPage(),
                    'perpage' => $request->query('pageSize'),
                    'total'   => $master->total(),
                ],
            ]);
        }

        return view('host/custom/provider/category/index')->with('master', $master);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        if ($request->ajax()) {

            return response()->json([
                'data' => [
                    'superClassify' => $this->getCategoryMasterList(),
                    'sort'          => 0,
                    'display'       => true,
                    'name'          => '',
                ],
            ]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'      => 'required',
                'parent_id' => 'required|numeric',
                'sort'      => 'required',
                'display'   => 'required',
            ]
        );
        if ($validator->fails()) {
            return redirect()->back();
        }

        /**
         * @var \App\B2BProject\Custom\Business\Store
         */
        $store = Auth::user()->store;//获取店铺信息

        try {
            \DB::transaction(function () use ($request, $store) {
                $data     = $request->only(['name', 'sort', 'display']);// 只取这些数据
                $category = GoodsCategory::create($data); //创建分类对象

                if ($request->input('parent_id') == 0) {
                    $category->parent_id = 0;
                    $category->save(); // 保存数据
                } else {
                    GoodsCategory::find($request->input('parent_id'))->children()->save($category);
                }

                $store->categories()->save($category); // 保存数据
            });

            if ($request->ajax()) {
                // 获取列表
                return $this->index($request);
            }

            return redirect()->route('account.category.index');
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Request $request
     * @param  int    $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        if ($request->ajax()) {
            $edit = Auth::user()->store->categories()->whereId($id)->firstOrFail();

            return response()->json([
                'data' => [
                    'edit_id'       => $edit->id,
                    'superClassify' => $this->getCategoryMasterList(),
                    'sort'          => $edit->sort,
                    'display'       => $edit->display,
                    'name'          => $edit->name,
                ],
            ]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'name'      => 'required',
                'parent_id' => 'required|numeric',
                'sort'      => 'required',
                'display'   => 'required',
            ]
        );

        if ($validator->fails()) {
            return redirect()->back();
        }

        try {
            $store = Auth::user()->store;//获取店铺信息

            \DB::transaction(function () use ($request, $store, $id) {
                $data     = $request->only(['name', 'sort', 'display']);// 只取这些数据
                $category = GoodsCategory::findOrFail($id); //创建分类对象

                $category->update($data);

                if ($request->input('parent_id') == 0) {
                    $category->parent_id = 0;
                    $category->save(); // 保存数据
                } else {
                    GoodsCategory::find($request->input('parent_id'))->children()->save($category);
                }
            });


            return redirect()->back();
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function forceUpdate(Request $request)
    {
        $validator = Validator::make(
            $request->except(['_token']),
            [
                'id'        => 'required|exists:goods_categories,id',
                'name'      => 'required',
                'parent_id' => 'required|numeric',
                'sort'      => 'required',
                'display'   => 'required',
            ]
        );

        if ($validator->fails()) {
            return redirect()->back();
        }

        $id = $request->id;

        try {
            $store = Auth::user()->store;//获取店铺信息

            \DB::transaction(function () use ($request, $store, $id) {
                $data     = $request->only(['name', 'sort', 'display']);// 只取这些数据
                $category = GoodsCategory::findOrFail($id); //创建分类对象

                $category->update($data);

                if ($request->input('parent_id') == 0) {
                    $category->parent_id = 0;
                    $category->save(); // 保存数据
                } else {
                    GoodsCategory::find($request->input('parent_id'))->children()->save($category);
                }
            });

            return $this->index($request);
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $goodsCategory = GoodsCategory::findOrFail($id);

        if ($goodsCategory->children()->count() > 0) {
            if ($request->ajax()) {
                return response()->json(['data' => '请确保该分类不存在下级分类后才可删除'], 403);
            }

            // 抛出 403 错误
            abort(403);
        }

        // 要求必须确保分类下不存在任何商品
        if ($goodsCategory->goods()->count() > 0) {
            if ($request->ajax()) {
                return response()->json(['data' => '请确保该分类下不存在商品后才可删除'], 403);
            }

            // 抛出 403 错误
            abort(403);
        }

        $goodsCategory->delete();

        if ($request->ajax()) {
            return $this->index($request);
        }

        return redirect()->back();
    }

    public function delete(Request $request)
    {
        return $this->destroy($request, $request->id);
    }

    public function information(Request $request)
    {
        $id       = $request->query('id');
        $type     = $request->query('type');
        $response = response('Error', 503);

        // TODO 来自前端网页的 ajax 请求，其中通过 GET 方式请求，但由于时间和协调问题，暂未遵循 RESTful 原则
        // 由于没有严格遵循 REST 原则，因此通过传统方式获取参数，type 表示请求的类型：0 为创建资源的页面，1 为创建二级资源的页面，2 为编辑页面
        switch ($type) {
            case 0:
                return $this->create($request);
                break;
            case 1:
                $response = response()->json([
                    'data' => [
                        'superClassify' => $this->getCategoryMasterList(),
                        'sort'          => 0,
                        'display'       => true,
                        'name'          => '',
                    ],
                ]);
                break;
            case 2:
                return $this->edit($request, $id);
                break;
        }

        return $response;
    }

    /**
     * 获取一级分类列表，列表格式根据前端定义返回
     *
     * @return array
     */
    protected function getCategoryMasterList()
    {
        $data[] = ['code' => 0, 'text' => '顶层分类'];
        // 获取上级分类
        $all = Auth::user()->store->categories()->MasterList()->get();

        foreach ($all as $item) {
            $data[] = [
                'code' => $item->id,
                'text' => $item->name,
            ];
        }

        return $data;
    }
}
